package app.util.image
{
	import flash.display.BitmapData;   
    import mx.graphics.codec.IImageEncoder;   
    import flash.utils.ByteArray;   
    import flash.utils.Endian;  
     
    public class BMPEncoder implements IImageEncoder   
    {   
        public function encode(bitmapData:BitmapData):ByteArray   
        {   
            var bmpWidth:int = bitmapData.width;   
            var bmpHeight:int = bitmapData.height;   
            var imageBytes:ByteArray = bitmapData.getPixels(bitmapData.rect);   
            var imageSize:int = imageBytes.length;   
            var imageDataOffset:int = 0x36;   
            var fileSize:int = imageSize + imageDataOffset;   
               
            var bmpBytes:ByteArray = new ByteArray();   
            bmpBytes.endian = Endian.LITTLE_ENDIAN;   
               
            bmpBytes.length = fileSize;   
            bmpBytes.writeByte(0x42);    
            bmpBytes.writeByte(0x4D);    
            bmpBytes.writeInt(fileSize);    
            bmpBytes.position = 0x0A;    
            bmpBytes.writeInt(imageDataOffset);   
            bmpBytes.writeInt(0x28);    
            bmpBytes.position = 0x12;    
            bmpBytes.writeInt(bmpWidth);   
            bmpBytes.writeInt(bmpHeight);   
            bmpBytes.writeShort(1);    
            bmpBytes.writeShort(32);    
            bmpBytes.writeInt(0);    
            bmpBytes.writeInt(imageSize);    
            bmpBytes.writeUnsignedInt(0x2e30);    
            bmpBytes.writeUnsignedInt(0x2e30);   
               
            bmpBytes.position = imageDataOffset;  
            var col:int = bmpWidth;   
            var row:int = bmpHeight;   
            var rowLength:int = col * 4;    
            try {   
                imageBytes.position = 0;   
                while (row--) {   
                       
                    bmpBytes.position = imageDataOffset + row*rowLength;   
                    col = bmpWidth;   
                    while (col--) {   
                        bmpBytes.writeInt(imageBytes.readInt());   
                    }   
                }      
            }catch(error:Error){       
            }   
            return bmpBytes;   
        }   
  
        public function get contentType():String   
        {   
            return null;   
        }   
  
        public function encodeByteArray(byteArray:ByteArray, width:int, height:int, transparent:Boolean = true):ByteArray   
        {   
            return null;   
        }          
    }   
}